package com.jd.tuning.jvm.async;

import lombok.SneakyThrows;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 本地调用异步化
 * 线程池
 */
public class AsyncDemoThreadPool {

  //实际项目不能调用一次创建一个线程池，放到外面去
  ThreadPoolExecutor threadPoolExecutor=
          new ThreadPoolExecutor(10,  //核心线程数
                  10,     //最大线程数=（核心线程+非核心线程）
                  //默认清空下指的是非核心线程的空闲时间
                  //如果allowCoreThreadTimeOut=ture :  核心线程或非核心线程允许的空闲时间
                  10L,
                  TimeUnit.SECONDS,
                  new LinkedBlockingDeque<>(),
                  Executors.defaultThreadFactory(),
                  new ThreadPoolExecutor.AbortPolicy());

  private  void subBiz1() throws InterruptedException {
    Thread.sleep(1000L);
    System.out.println(new Date()+"subBiz1");
  }

  private  void subBiz2() throws InterruptedException {
    Thread.sleep(1000L);
    System.out.println(new Date()+"subBiz2");
  }

  private  void saveOpLog() throws InterruptedException {
    threadPoolExecutor.submit(new SaveOpLogThreadA());
  }

  private  void biz() throws InterruptedException{
    this.subBiz1();
    saveOpLog();
    this.subBiz2();
  }

  public static void main(String[] args) throws InterruptedException {
    new AsyncDemoThreadPool().biz();
  }
}

class SaveOpLogThreadA implements  Runnable{
  @SneakyThrows
  @Override
  public void run() {
    Thread.sleep(1000L);
    System.out.println(new Date()+"插入操作日志");
  }
}
